package com.dreamstations.changshads.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.dreamstations.changshads.R;
import com.dreamstations.changshads.adapter.DSRvAdapter;
import com.dreamstations.changshads.entity.Article;
import com.dreamstations.changshads.entity.BaseBean;
import com.dreamstations.changshads.fragment.ArticleDetailPagerFragment;
import com.dreamstations.changshads.util.DSParser;
import com.dreamstations.changshads.util.DSRequest;
import com.dreamstations.changshads.util.L;
import com.dreamstations.changshads.util.RecycleViewDivider;
import com.dreamstations.changshads.util.RequestType;
import com.squareup.picasso.Picasso;
import com.zhy.base.adapter.ViewHolder;
import com.zhy.base.adapter.recyclerview.OnItemClickListener;

import java.util.ArrayList;
import java.util.List;

public class ArticleDetailActivity extends AppCompatActivity {
    private final static boolean ISDEV = false;
    private final static String TAG = ArticleDetailActivity.class.getName();
    private final static String testContent = "[{\"url\":\"/NewParty/image/other/work/201509230944137453.jpg\",\"doc\":\"111\"},{\"url\":\"/NewParty/image/other/work/201509230944137453.jpg\",\"doc\":\"222\"},{\"url\":\"/NewParty/image/other/work/201509230944137453.jpg\",\"doc\":\"333\"}]";

//    private List<String> articleUrls;
//    private List<String> articleDocs;
    private BaseBean data;
    private ArrayList<Article> articleList;

    private RecyclerView recyclerView;
    private DSRvAdapter<Article> adapter;

    private ImageView titlePic;
//    private String title;
//    private String content;
//    private String cover;
    private Picasso picasso;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_acticle_detail);
        picasso = Picasso.with(getApplicationContext());
//        articleUrls = new ArrayList<>();
//        articleDocs=new ArrayList<>();

        recyclerView = (RecyclerView) findViewById(R.id.detail_recycler);
        titlePic = (ImageView) findViewById(R.id.detail_tool_img);
        Toolbar toolbar = (Toolbar) findViewById(R.id.detail_toolbar);
        toolbar.setNavigationIcon(R.drawable.abc_ic_ab_back_mtrl_am_alpha);
        setSupportActionBar(toolbar);
        toolbar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        initRecyclerView();

        //最后绑定数据
        if (ISDEV) {
            loadMockData();
        } else {
            loadArticle();
        }
        String cover=data.getCover();
        if (cover != null && !cover.equals("")) {
            L.i(TAG, "=>loadPic:" + cover);
            picasso.load(cover)
                    .error(R.drawable.img_default)
                    .tag(getApplication())
                    .into(titlePic);
        }
        ((TextView) findViewById(R.id.detail_title)).setText(data.getTitle());
        setTitle(data.getTitle());
    }

    private void initRecyclerView() {

        DSRvAdapter.RvSupport<Article> item = new DSRvAdapter.RvSupport<Article>() {
            @Override
            public int getItemViewType(Article data) {
                return 0;
            }

            @Override
            public ViewHolder createHolder(Context context, ViewGroup parent, int viewType) {
                L.i(TAG, "=>createHolder:" + viewType);
                ViewHolder holder = ViewHolder.get(context, null, parent, R.layout.article_list_item, -1);
//                if (viewType == 0) {
//                    holder = ViewHolder.get(context, null, parent, R.layout.articledetail_imageview, -1);
//                } else {
//                    holder = ViewHolder.get(context, null, parent, R.layout.articledetail_textview, -1);
//                }
                return holder;
            }

            @Override
            public void convert(ViewHolder holder, Article data) {
                holder.setText(R.id.article_item_textview, data.getDoc());
                String url = data.getUrl();
                if (url == null || url.equals("")) return;
                ImageView imageView = holder.getView(R.id.article_item_imageview);
                L.i(TAG,"=>loadItemPic:"+DSRequest.SERVER_BASE1+data.getUrl());
                picasso.load(DSRequest.SERVER_BASE1+data.getUrl())
                        .tag(ArticleDetailActivity.this)
                        .placeholder(R.drawable.img_loading)
                        .error(R.drawable.img_default)
                        .into(imageView);
            }
        };

        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        recyclerView.addItemDecoration(new RecycleViewDivider(getApplicationContext(), LinearLayoutManager.HORIZONTAL
                , 16, android.R.color.background_light));
        adapter = new DSRvAdapter(getApplicationContext(), new ArrayList<Article>(), item);
        adapter.setOnItemClickListener(new OnItemClickListener<Article>() {
            @Override
            public void onItemClick(ViewGroup parent, View view, Article o, int position) {
                Log.d("clickImage", "点击了:" + position);
//                String[] array = new String[articleUrls.size()];            //用于将 articleUrls 转为数组
//                if (o.getUrl().equals("doc")) return;
//                ArticleDetailPagerFragment fragment = ArticleDetailPagerFragment.newInstance(position,
//                        articleUrls.toArray(array));
//                getSupportFragmentManager().beginTransaction()
//                        .add(R.id.detail_frame, fragment)
//                        .setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN)
//                        .addToBackStack(null)
//                        .commit();
                Intent intent=new Intent(ArticleDetailActivity.this,PicTopicActivity.class);
                intent.putExtra("index",position);
                intent.putExtra("title",data.getTitle());
                intent.putParcelableArrayListExtra("data",articleList);
                startActivity(intent);

            }

            @Override
            public boolean onItemLongClick(ViewGroup parent, View view, Article o, int position) {
                return false;
            }
        });
        recyclerView.setAdapter(adapter);
    }


    private void loadMockData() {
//        List<Article> articleList = new ArrayList<>();
//        for (int i = 0; i < 3; i++) {
//            Article article = new Article("doc", "　　习近平指出，我们党在中国这样一个有着13亿人口的大国执政，面对着十分复杂的国内外环境，肩负着繁重的执政使命，如果缺乏理论思维的有力支撑，是难以战胜各种风险和困难的，也是难以不断前进的。党的各级领导干部特别是高级干部，要原原本本学习和研读经典著作，努力把马克思主义哲学作为自己的看家本领，坚定理想信念，坚持正确政治方向，提高战略思维能力、综合决策能力、驾驭全局能力，团结带领人民不断书写改革开放历史新篇章。(新华社北京12月4日电)");
//            articleList.add(article);
//            Article article2 = new Article("url", "http://i1.buimg.com/3ee901bfed3694d3s.png");
//            articleList.add(article2);
//            articleUrls.add(article2.getDoc());
//        }
//        cover = "http://i1.buimg.com/2e7fa7973d800abas.png";
//        title = "毛泽东的抗日国际统一战线思想及其历史贡献";
//        adapter.setItemDatas(articleList);
    }

    @Override
    protected void onPause() {
        picasso.cancelTag(ArticleDetailActivity.this);
        super.onPause();
    }

    private void loadArticle() {
        try {
            data = (BaseBean) getIntent().getSerializableExtra("data");
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (data == null) {
            Toast.makeText(getApplicationContext(), "加载文章失败，请刷新重试", Toast.LENGTH_SHORT).show();
            return;
        }
//        title = o.getTitle();
//        cover = o.getCover();
        final String content = data.getContent();
        //解析特供数据并且填充内容
        if (content == null || content.equals("")) {
            Toast.makeText(getApplicationContext(), "加载文章失败，请刷新重试", Toast.LENGTH_SHORT).show();
            return;
        }
        new Handler().post(new Runnable() {
            @Override
            public void run() {
                try {
                    articleList = (ArrayList<Article>) DSParser.parse(RequestType.PARSE_ARTICLE, content);
                    adapter.setItemDatas(articleList);
//                    for (Article a : result) {
//                        articleUrls.add(a.getUrl());
//                        articleDocs.add(a.getDoc());
//                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    Toast.makeText(getApplicationContext(), "加载文章失败，请刷新重试", Toast.LENGTH_SHORT).show();
                }
            }
        });
    }
}
